<template>
  <div class="contract-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="6" animated />
    </div>

    <!-- 合同主体 -->
    <template v-else>
      <!-- 返回按钮 -->
      <div class="back-button">
        <el-button type="info" @click="goBack">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
      </div>

      <!-- 合同头部 -->
      <el-card class="contract-header">
        <h1 class="contract-title">房屋租赁合同</h1>
        <el-divider />

        <!-- 合同双方信息 -->
        <el-descriptions title="合同主体" :column="2" border>
          <el-descriptions-item label="出租方（甲方）">
            <div class="party-info">
              <div class="name">{{ orderData.owner.name }}</div>
              <el-tag size="small" type="info">
                <el-icon><User /></el-icon>
                {{ orderData.owner.idcard }}
              </el-tag>
            </div>
          </el-descriptions-item>

          <el-descriptions-item label="承租方（乙方）">
            <div class="party-info">
              <div class="name">{{ orderData.customer.name }}</div>
              <el-tag size="small" type="info">
                <el-icon><User /></el-icon>
                {{ orderData.customer.idcard }}
              </el-tag>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 房屋基本信息 -->
      <el-card class="section-card">
        <h2 class="section-title">房屋信息</h2>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="房屋地址">
            {{ orderData.house.address }}
          </el-descriptions-item>
          <el-descriptions-item label="户型结构">
            {{ houseLayout }}
          </el-descriptions-item>
          <el-descriptions-item label="租赁状态">
            <el-tag :type="statusTagType">{{ statusText }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="合同编号">
            {{ orderData.orderNumber }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 租赁条款 -->
      <el-card class="section-card">
        <h2 class="section-title">租赁条款</h2>
        <div class="lease-terms">
          <div class="term-item">
            <el-icon><Calendar /></el-icon>
            <span class="term-label">租赁周期：</span>
            {{ orderData.startDate }} 至 {{ orderData.endDate }}
            <el-tag type="success"> 共 {{ leaseDays }} 天 </el-tag>
          </div>

          <div class="term-item">
            <el-icon><Money /></el-icon>
            <span class="term-label">租金明细：</span>
            月租金 ¥{{ orderData.monthRent }}
            <el-divider direction="vertical" />
            总金额 ¥{{ orderData.totalAmount }}
            <el-divider direction="vertical" />
            押金 ¥{{ (orderData.totalAmount * 0.15).toFixed(2) }}
          </div>
        </div>
      </el-card>

      <!-- 合同条款 -->
      <el-card class="section-card">
        <h2 class="section-title">合同条款</h2>
        <div class="clauses">
          <div
            v-for="(clause, index) in contractClauses"
            :key="index"
            class="clause-item"
          >
            <div class="clause-header">
              <div class="clause-index">第{{ index + 1 }}条</div>
              <div class="clause-title">{{ clause.title }}</div>
            </div>
            <div class="clause-content">{{ clause.content }}</div>
          </div>
        </div>
      </el-card>

      <!-- 签署区域 -->
      <el-card v-if="showSignArea" class="signature-section">
        <h2 class="section-title">签署确认</h2>
        <div class="signature-wrapper">
          <canvas
            v-show="!isViewMode"
            ref="signaturePad"
            class="signature-canvas"
          ></canvas>
          <div v-if="isViewMode" class="signature-preview">
            <el-image
              v-if="orderData.signature"
              :src="orderData.signature"
              fit="contain"
            />
            <el-empty v-else description="未签署" />
          </div>
          <div v-if="!isViewMode" class="signature-controls">
            <el-button type="danger" @click="clearSignature">
              <el-icon><Delete /></el-icon>
              清除签名
            </el-button>
            <el-button type="success" @click="undoLastStroke">
              <el-icon><RefreshLeft /></el-icon>
              撤销上一步
            </el-button>
          </div>
        </div>
      </el-card>

      <!-- 操作按钮区域 -->
      <div class="action-buttons">
        <!-- 签署按钮 -->
        <el-button
          v-if="showSignButton"
          type="primary"
          size="large"
          :loading="submitting"
          @click="handleSubmit"
        >
          <el-icon><DocumentChecked /></el-icon>
          确认签署合同
        </el-button>

        <!-- 退租按钮 -->
        <el-button
          v-if="showCancelLeaseButton"
          type="warning"
          size="large"
          @click="showCancelDialog = true"
        >
          <el-icon><House /></el-icon>
          申请退租
        </el-button>
      </div>

      <!-- 退租对话框 -->
      <el-dialog
        v-model="showCancelDialog"
        title="申请退租"
        width="500px"
        :close-on-click-modal="false"
      >
        <el-form
          ref="cancelFormRef"
          :model="cancelForm"
          :rules="cancelRules"
          label-width="80px"
        >
          <el-form-item label="退租原因" prop="reason">
            <el-input
              v-model="cancelForm.reason"
              type="textarea"
              :rows="4"
              placeholder="请详细说明退租原因（至少10个字符）"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="showCancelDialog = false">取消</el-button>
          <el-button
            type="warning"
            :loading="submittingCancel"
            @click="submitCancelLease"
          >
            提交申请
          </el-button>
        </template>
      </el-dialog>
    </template>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  computed,
  onMounted,
  nextTick,
  watch,
  onBeforeUnmount,
} from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  User,
  Calendar,
  Money,
  DocumentChecked,
  Delete,
  RefreshLeft,
  House,
  ArrowLeft,
} from "@element-plus/icons-vue";
import SignaturePad from "signature_pad";
import api from "@/api/modules/order";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/stores/user";

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

const isTenant = computed(() => {
  return userStore.userInfo.roles.some((r) => r.name === "ROLE_Tenant");
});

// 订单数据
const orderData = reactive({
  id: null,
  orderNumber: "",
  status: -2,
  owner: { name: "", idcard: "" },
  customer: { name: "", idcard: "" },
  house: { address: "", bedroom: 0, livingRoom: 0, toilet: 0 },
  signature: null,
  monthRent: 0,
  totalAmount: 0,
  startDate: "",
  endDate: "",
  houseId: 0,
});

// 组件状态
const loading = ref(true);
const submitting = ref(false);
const signaturePad = ref(null);
let signPad = null;

// 退租相关状态
const showCancelDialog = ref(false);
const submittingCancel = ref(false);
const cancelForm = reactive({ reason: "" });
const cancelFormRef = ref();

const signatureStatus = ref("请签署您的姓名");
const signatureHistory = ref([]);
const contractData = reactive({});

// 模式判断
const isViewMode = computed(() => route.query.mode === "view");
const isSignMode = computed(() => route.query.mode === "sign");

// 显示逻辑控制
const showSignArea = computed(() => {
  return isSignMode.value || (isViewMode.value && contractData.signature);
});

const showSignButton = computed(() => {
  return isSignMode.value && contractData.status === -2;
});

// 获取合同数据时处理签署状态
const fetchContractData = async () => {
  const { data } = await api.getOrderDetail(route.query.orderId);
  Object.assign(contractData, data);
};

const depositAmount = computed(() => {
  return orderData.totalAmount * 0.15;
});

// 合同条款内容
const contractClauses = reactive([
  {
    title: "房屋用途",
    content: "租赁房屋仅限于居住用途，未经甲方书面同意不得改变房屋用途",
  },
  {
    title: "租金支付",
    content: "乙方应于每月5日前支付当月租金，逾期超过15天甲方有权终止合同",
  },
  {
    title: "押金条款",
    content: "合同终止后经房屋验收无损坏，押金无息退还。扣除押金情形包括...",
  },
  {
    title: "维修责任",
    content: "自然损耗由甲方负责维修，乙方使用不当造成的损坏由乙方承担",
  },
  {
    title: "转租限制",
    content: "未经甲方书面同意，乙方不得转租、分租或出借房屋",
  },
]);

// 计算属性
const leaseDays = computed(() => {
  const start = new Date(orderData.startDate);
  const end = new Date(orderData.endDate);
  return Math.ceil((end - start) / (1000 * 60 * 60 * 24));
});

const showCancelLeaseButton = computed(() => {
  return orderData.status === 0 && isTenant.value;
});
const cancelRules = {
  reason: [
    { required: true, message: "必须填写退租原因", trigger: "blur" },
    { min: 10, message: "原因说明至少10个字符", trigger: "blur" },
  ],
};

const submitCancelLease = async () => {
  try {
    await cancelFormRef.value.validate();
    submittingCancel.value = true;

    await api.cancelOrder(orderData.id, cancelForm.reason);
    ElMessage.success("退租申请已提交");

    await fetchOrderDetail();
    showCancelDialog.value = false;
    cancelForm.reason = "";
  } catch (error) {
    ElMessage.error(error.message || "操作失败");
  } finally {
    submittingCancel.value = false;
  }
};

const statusText = computed(() => {
  const statusMap = {
    "-2": "待签署",
    "-1": "待支付",
    0: "生效中",
    1: "已退租",
    2: "待审核",
  };
  return statusMap[orderData.status] || "未知状态";
});

const statusTagType = computed(() => {
  const typeMap = {
    "-2": "warning",
    "-1": "danger",
    0: "success",
    1: "info",
    2: "",
  };
  return typeMap[orderData.status] || "info";
});

const houseLayout = computed(() => {
  const h = orderData.house;
  return `${h.bedroom}室${h.livingRoom}厅${h.toilet}卫`;
});

// 初始化签名板
const initSignaturePad = async () => {
  if (!signaturePad.value) {
    console.error(
      "Canvas元素未找到，当前DOM状态:",
      document.querySelector(".signature-canvas")
    );
    return;
  }
  try {
    const canvas = signaturePad.value;
    const ctx = canvas.getContext("2d");

    // 处理高清屏幕显示
    const ratio = window.devicePixelRatio || 1;
    canvas.width = canvas.offsetWidth * ratio;
    canvas.height = canvas.offsetHeight * ratio;
    ctx.scale(ratio, ratio);

    signPad = new SignaturePad(canvas, {});
  } catch (error) {
    console.error("签名板初始化失败:", error);
    ElMessage.error("签名功能初始化失败，请刷新页面重试");
  }
};

// 新增撤销功能
const undoLastStroke = () => {
  if (signatureHistory.value.length > 0) {
    signatureHistory.value.pop();
    signPad.fromData(signatureHistory.value);
    updateSignatureStatus();
  }
};

// 增强清除功能
const clearSignature = () => {
  signPad.clear();
  signatureHistory.value = [];
  updateSignatureStatus();
};

// 触摸事件处理
const handleTouchStart = (e) => {
  e.preventDefault();
  signPad._handleMouseDown(e.touches[0]);
};

const handleTouchEnd = (e) => {
  e.preventDefault();
  signPad._handleMouseUp();
};

// 状态提示更新
const updateSignatureStatus = () => {
  signatureStatus.value = signPad.isEmpty()
    ? "请签署您的姓名"
    : "签名有效，可点击撤销按钮修改";
};

onBeforeUnmount(() => {
  if (signPad) {
    signPad.off();
    signPad = null;
  }
});

const fetchOrderDetail = async () => {
  try {
    const { data } = await api.getOrderDetail(route.query.orderId);
    Object.assign(orderData, data);
    Object.assign(contractData, data);
    console.log("当前订单状态:", {
      statusCode: orderData.status,
      type: typeof orderData.status,
      mappedStatus: statusText.value,
    });
    console.log("当前订单数据:", orderData);
    // 监听 signaturePad 的变化并在其存在时初始化签名板
    watch(
      signaturePad,
      (newVal) => {
        if (newVal) {
          initSignaturePad();
        }
      },
      { immediate: true }
    );
  } catch (error) {
    ElMessage.error("获取合同数据失败");
  } finally {
    loading.value = false;
  }
};

// 提交签署
const handleSubmit = async () => {
  if (!signPad || signPad.isEmpty()) {
    return ElMessage.warning("请先完成电子签名");
  }

  submitting.value = true;
  try {
    const signatureData = signPad.toDataURL();

    // 调用签署接口
    await api.confirmOrder(orderData.id);

    ElMessage.success("合同签署成功");
    router.push({
      name: "Pay",
      query: {
        orderId: orderData.id,
        houseId: orderData.houseId,
        amount: orderData.totalAmount + depositAmount.value,
      },
    });
  } catch (error) {
    ElMessage.error("签署失败: " + error.message);
  } finally {
    submitting.value = false;
  }
};

// 返回按钮点击事件
const goBack = () => {
  router.back();
};

onMounted(async () => {
  await userStore.fetchUserInfo();
  await fetchOrderDetail();
});
</script>

<style scoped lang="css">
.contract-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
  background: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.contract-header {
  margin-bottom: 30px;

  .contract-title {
    text-align: center;
    color: #2c3e50;
    font-size: 28px;
    margin: 20px 0;
  }
}

.signature-preview {
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px dashed #eee;
  border-radius: 8px;
  background: #fafafa;
}

.signature-preview .el-empty {
  padding: 40px 0;
}

.section-card {
  margin-bottom: 25px;
  border-radius: 8px;

  .section-title {
    color: #409eff;
    font-size: 20px;
    margin: 15px 0;
    padding-left: 10px;
    border-left: 4px solid #409eff;
  }
}

.lease-terms {
  padding: 15px;

  .term-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 15px;
    margin: 10px 0;
    background: #f8f9fa;
    border-radius: 6px;

    .term-label {
      font-weight: 500;
      color: #606266;
    }

    .el-icon {
      font-size: 18px;
      color: #409eff;
    }
  }
}

.action-buttons {
  margin: 40px 0;
  text-align: center;

  .el-button {
    padding: 18px 50px;
    font-size: 18px;
    border-radius: 8px;
  }
}

.clause-item {
  margin: 20px 0;
  padding: 15px;
  border-bottom: 1px solid #eee;

  .clause-header {
    display: flex;
    align-items: center;
    margin-bottom: 10px;

    .clause-index {
      color: #409eff;
      font-weight: 500;
      margin-right: 15px;
    }

    .clause-title {
      font-weight: 500;
      color: #303133;
    }
  }

  .clause-content {
    color: #606266;
    line-height: 1.8;
    text-indent: 2em;
  }
}

.party-info {
  .name {
    font-weight: 500;
    margin-bottom: 5px;
  }

  .el-tag {
    padding: 5px 10px;
  }
}

.signature-section {
  .signature-canvas {
    width: 100%;
    height: 200px;
    border: 2px solid #409eff;
    border-radius: 8px;
    background: #ffffff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    touch-action: none;
  }

  .signature-controls {
    margin-top: 15px;
    display: flex;
    justify-content: space-between;
    gap: 10px;

    .el-button {
      flex: 1;
      padding: 12px 20px;
    }
  }

  .signature-tips {
    margin-top: 15px;

    :deep(.el-alert__title) {
      font-size: 14px;
      color: #606266;
    }
  }
}

.back-button {
  margin-bottom: 20px;
  text-align: left;

  .el-button {
    padding: 10px 20px;
    font-size: 16px;
    border-radius: 6px;
  }
}
</style>
